// shared_ptr
// 1.shared_ptr为共享指针，意味我们共同指向一块空间；
// 里面采用引用计数，当有别的shared_ptr指向我这块空间时
// 就增加引用计数，当引用计数减为0的时候，才释放这块空间。

#include <iostream>
using namespace std;

template <typename T>
class Shared_ptr
{
    protected:
        T *_ptr;
        int * _pCount;
    public:
        Shared_ptr(T * ptr) :_ptr(ptr) ,_pCount(new int(1)){}
        ~Shared_ptr()
        {
            (*_pCount)--;
            if((*_pCount) == 0)
            {
                delete _ptr;
                delete _pCount;
                cout<<" !SharedPtr()"<<endl;
            }
        }

        Shared_ptr(const Shared_ptr<T> & ap):_ptr(ap._ptr),_pCount(ap._pCount)
        {
            (*_pCount)++;
        }

        Shared_ptr<T>& operator= (const Shared_ptr<T> & ap )
        {
            if(_ptr != ap._ptr)
            {
                if(--(*_pCount) == 0)
                {
                    delete _ptr;
                    delete _pCount;
                }
                _ptr = ap._ptr;
                _pCount = ap._pCount;
                (*_pCount)++;
            }
            return *this;
        }

        T& operator* ()
        {
            return *_ptr;
        }
        T* operator-> ()
        {
            return _ptr;
        }


};

int main()
{
    Shared_ptr<int> p1(new int(5));
    {
        Shared_ptr<int> p2(p1);
        
        cout<<*p2<<endl;

    }
    cout<<*p1<<endl;
    
    return 0;
}